/**
 * Project: apollo-base-commons
 * 
 * File Created at 2016年10月16日
 * 
 * Copyright 2015-2016 dx.com Croporation Limited.
 * All rights reserved.
 *
 * This software is the confidential and proprietary information of
 * DongXue software Company. ("Confidential Information").  You shall not
 * disclose such Confidential Information and shall use it only in
 * accordance with the terms of the license agreement you entered into
 * with dx.com.
 */
package com.dx.pf.commons.reflect;

import java.io.File;
import java.io.FileFilter;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.List;

import com.dx.pf.commons.io.IOUtil;
import com.dx.pf.commons.utils.FileUtil;

/** 
* @ClassName: JarClassLoader 
* @Description: 外部Jar的类加载器
* @author wuzhenfang(wzfbj2008@163.com)
* @date 2016年10月16日 下午9:31:41 
* @version V1.0 
*/
public class JarClassLoader extends URLClassLoader{

	// ------------------------------------------------------------------- Constructor start
	public JarClassLoader() {
		this(new URL[] {});
	}

	public JarClassLoader(URL[] urls) {
		super(urls, ClassUtil.getClassLoader());
	}
	// ------------------------------------------------------------------- Constructor end

	/**
	 * 加载Jar到ClassPath
	 * @param jarFile jar文件或所在目录
	 * @return JarClassLoader
	 * @throws Exception 
	 */
	public static JarClassLoader loadJar(File jarFile) throws Exception {
		final JarClassLoader loader = new JarClassLoader();
		try {
			loader.addJar(jarFile);
		} finally {
			IOUtil.close(loader);
		}
		return loader;
	}

	/**
	 * 加载Jar文件，或者加载目录
	 * @param jarFile jar文件或者jar文件所在目录
	 * @throws Exception 
	 */
	public void addJar(File jarFile) throws Exception {
		final List<File> jars = loopJar(jarFile);
		try {
			for (File jar : jars) {
				super.addURL(jar.toURI().toURL());
			}
		} catch (MalformedURLException e) {
			throw new Exception(e);
		}
	}

	@Override
	public void addURL(URL url) {
		super.addURL(url);
	}

	// ------------------------------------------------------------------- Private method start
	/**
	 * 递归获得Jar文件
	 * @param file jar文件或者包含jar文件的目录
	 * @return jar文件列表
	 */
	private static List<File> loopJar(File file) {
		return FileUtil.loopFiles(file, new FileFilter() {

			@Override
			public boolean accept(File pathname) {
				final String path = pathname.getPath();
				if (path != null && path.endsWith(".jar")) {
					return true;
				}
				return false;
			}
		});
	}
	// ------------------------------------------------------------------- Private method end
}
